##
## cwsAdmin.py 
##
## Master script for cwsAdmin application.
## (ie create database, create user)
##
## Author: Shannon Eric Peevey <speeves@erikin.com>, 17 Jan 2004
##
# import the classes that we need
import os, time, string, re, sys, readline
from xml.dom import minidom, Node
from optparse import OptionParser
from configobj import ConfigObj
# pgenerate.py needs to be in the path to be found
# this class creates random passwords
import Pgenerate
from Error import *

VERSION = "0.1"

def GetConfigurationDirectories():
    """ Get the listing of possible configuration which can be called
    with the -f flag from the command line.  This is done by:

    1. getting a listing of the directories in /path/to/cwsAdmin/conf
    2. return list
    """
    confOptions = os.listdir("conf/")

    for d in confOptions:
        if d[0] == '.':
            del confOptions[confOptions.index(d)]

    return confOptions


# create our command line options and help text
def usage(confOptions):
    """ Generate the usage message for the -h flag, or a wrong option """
    # generate string for -f flag options
    iterator = 1
    numberOfConfDirectories = len(confOptions)
    configurationOptions = ""
    for d in confOptions:
        configurationOptions = configurationOptions + d
        if iterator < numberOfConfDirectories:
            configurationOptions = configurationOptions + "|"
        iterator = iterator + 1
    
    usageText = "usage: %prog -f (" + configurationOptions + ") "
    parser = OptionParser(usageText, version=VERSION)

    parser.add_option("-f", "--webfarm", action="store", type="string", dest="webFarm",
                  help="(" + configurationOptions + ") determine which web farm to perform tasks on (apache farm specific)")

    parser.add_option("-w", "--wizard", action="store_true", dest="wizard",
                  help="Wizard for creation of apache subweb or vhost, mysql or mssql database, ldap user mgmt, and email notification")
    parser.add_option("-d", "--fqdn", action="store", type="string", dest="fqdn",
                  help="Apache - vHost FQDN (ie www.example.com)")
    parser.add_option("-s", "--subweb", action="store", type="string", dest="subweb",
                  help="Apache - destination subweb (ie mysubweb)")

    parser.add_option("-o", "--sourcedn", action="store", type="string", dest="sourcedn",
                  help="LDAP - Source Dn (ie cn=mysubweb,ou=my_example_com,ou=applications,dc=example,dc=com)")
    parser.add_option("-e", "--destinationdn", action="store", type="string", dest="destinationdn",
                  help="LDAP - Destination Dn (ie cn=mysubweb,ou=my_example_com,ou=applications,dc=example,dc=com)")
    parser.add_option("-a", "--ldapsearch", action="store", type="string", dest="ldapsearch",
                  help="LDAP - LDAP Filter String (ie cn=mysubweb or uid=abc0001)")

    parser.add_option("-v", "--verbose",
                      action="store_true", dest="verbose")
    parser.add_option("-q", "--quiet",
                      action="store_false", dest="verbose")

    (options, args) = parser.parse_args()

    if options.webFarm:
        return options
    else:
       parser.error("No Web Farm Specified")

try:
    from Utility import *
except ImportError:
    pass


#main function
if __name__ == '__main__':
    # grab the command line options
    confOptions = GetConfigurationDirectories()
    opts = usage(confOptions)

    # set apache variables based on farm
    # here we set the farm on which we want to perform apache actions
    # the current options are "www" or "dynofarm"...
    if opts.webFarm:
        webFarm = opts.webFarm
    else:
        # default to the dynofarm
        webFarm = "dynofarm"

    ## loop through the configuration directories in:
    #
    #  /path/to/cwsAdmin/conf/
    for confDir in confOptions:
        if webFarm == confDir:
            config = ConfigObj('conf/' + confDir + '/config.txt')
            # Create a Sessions dictionary for adding variables and accessing them
            config['Session'] = {}
            config['Session']['Analog'] = {}
            config['Session']['Apache'] = {}
            config['Session']['Coldfusion'] = {}
            config['Session']['Email'] = {}
            config['Session']['Htgroup'] = {}
            config['Session']['Ldap'] = {}
            config['Session']['Mssql'] = {}
            config['Session']['Mysql'] = {}
            config['Session']['Postgresql'] = {}
            
            config['Session']['Analog']['CurrentServer'] = "0"
            config['Session']['Apache']['CurrentServer'] = "0"
            config['Session']['Coldfusion']['CurrentServer'] = "0"
            config['Session']['Email']['CurrentServer'] = "0"
            config['Session']['Htgroup']['CurrentServer'] = "0"
            config['Session']['Ldap']['CurrentServer'] = "0"
            config['Session']['Mssql']['CurrentServer'] = "0"
            config['Session']['Mysql']['CurrentServer'] = "0"
            config['Session']['Postgresql']['CurrentServer'] = "0"

            # loop through the opts and assign the k=v pairs to config['Options']
            for k,v in opts.__dict__.items():
                config['Session'][k] = v

            
    #print config
    # instantiate the standard error routines
    errorObject = StandardErrors()
    utilityObject = UtilityFunc()
    
    ### grab XML ###
    # parse the file, and associate it with a variable
    xmldoc = minidom.parse(config['General']['menuFile'])
    # set the firstChild node to the variable menu
    menu = xmldoc.firstChild
    ### finish grabbing XML ###
        
    #first we introduce ourselves
    print "Welcome to the cwsAdmin Program!!"
    print ""
    print "This program will gather the necessary information to create a new web, user, and add these"
    print "people into the correct files."
    print ""

    print "Setting Web Farm as ", webFarm
    print ""

    if config['Session']['wizard']:
        try:
            from Wizard import *
        except ImportError:
            pass
        
        w = WizardFunc()
        w.AddWizard(config, menu, errorObject, utilityObject)
    else:
        # call Utility.MenuCreate() to create XML configured menus
        utilityObject.MenuCreate(config, menu, errorObject, utilityObject)
    
    if config['Coldfusion']["useCf"] == '1':
        print "Please, don't forget to create the"
        print "DSN in the ColdFusion Administrator"
    print "Thank you for using the cwsAdmin Program"
    print "Good-bye!"
